package com.ts.api.http.receive.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyLeTianHuaV2;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeLeTianHuaV2;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 *
 *  乐天花 V2安心分期
 *
 *  @author WJB
 */
@ApiReceive(apiClientId = "1932863542109556736",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5LeTianHuaV2AnXin implements ApiReceivePhoneMd5ConvertHandler {

    private static final String KEY = "e42fef012he56789";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());
        String channelCode = String.valueOf(map.get("channelCode"));
        String content = String.valueOf(map.get("content"));

        //  传递什么，验证什么Key
        Assert.isNotEmptyThrows(channelCode, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("channelCode")));
        Assert.isNotEmptyThrows(content, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("content")));

        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", channelCode);
            newMap.put("content", content);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        //  获取未解密数据
        String content = paramMap.get("content");

        //  文档解密过程
        AES cbc = AES.createEcb(KEY.getBytes());
        String decrypt = cbc.decryptFromBase64Str(content);
        //  这里不需要额外参数-所以不用加载map
        return new ApiReceiveDecrypt(decrypt);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeLeTianHuaV2 parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeLeTianHuaV2.class);
        //  拷贝成系统的实体类
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        boolean suc = dataExchangeMessage.hasBizSuc();
        if (!suc) {
            resultMap.put("code", 0);
            resultMap.put("msg", dataExchangeMessage.getBizMsg());
            return resultMap;
        }

        resultMap.put("code", 200);
        resultMap.put("msg", "撞库成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  公司名称
            dataMap.put("deptCompanyName", dataExchangeMessage.getOrgName());
            //  产品名称
            dataMap.put("deptProductName", dataExchangeMessage.getDisplayName());
            //  产品logo
            dataMap.put("deptLogoUrl", dataExchangeMessage.getLogoPath());
            //  价格
            dataMap.put("downSellMoney", dataExchangeMessage.getPrice());
            //  用户授权页面地址
            dataMap.put("jumpUrl", dataExchangeMessage.getCallUrl());
            //  订单号
            dataMap.put("downOrderId", ApiContext.REQ_ID.get());
            //  授权文件集合
            dataMap.put("authList", CollUtils.newArrayList(protocolList -> {
                Map<String, Object> protocol = MapUtils.newLinkedHashMap();
                //  协议名称
                protocol.put("authName", "个人信息授权协议");
                //  协议地址
                protocol.put("authUrl", "https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
                protocolList.add(protocol);
            }));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyLeTianHuaV2 parse = apiReceiveDecrypt.parse(ApiReceiveApplyLeTianHuaV2.class);
        //  拷贝成系统的实体类
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        boolean suc = applyMessage.hasBizSuc();
        if (!suc) {
            resultMap.put("code", 0);
            resultMap.put("msg", applyMessage.getBizMsg());
            return resultMap;
        }

        resultMap.put("code", 200);
        resultMap.put("msg", "进件成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            //  撞库返回的订单号
            dataMap.put("downOrderId", ApiContext.REQ_ID.get());
        }));
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {

        //  sex 性别（0-女;1-男（默认））
        //  sex 性别：0：男 1：女
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "0", "1")
                    .when(sex, "1", "0")
                    .end();
            apiUserRequest.setSex(sexChoose);
        }

        //  贷款金额(元)
        //  loanAmount 贷款金额
        //  1 3万以下
        //  2 5万-10万
        //  3 10万-20万
        //  4 20万以上
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String value = ApiDictUtils.convertLoanAmount(loanAmount,true);
            apiUserRequest.setLoanAmount(value);
        }

        //  credit 信用情况：0未知  1-有逾期 ；2-无逾期
        //  overdue 逾期
        //  1 无逾期
        //  2 当前有逾期
        //  3 一年以内无逾期
        String creditStatus = apiUserRequest.getOverdue();
        if (ValidParam.isNotEmpty(creditStatus)) {
            String value = ChooseEq.create()
                    .when(creditStatus, "1", "2")
                    .when(creditStatus, "2", "1")
                    .end();
            apiUserRequest.setOverdue(value);
        }

        // education 学历：0-未知；1-初中及以下； 2-高中；3-大专； 4本科；5 研究生及以上
        // educationAttainment 学历
        // 1 初中及以下
        // 2 中专
        // 3 高中
        // 4 大专
        // 5 本科
        // 6 研究生及以上
        String educationAttainment = apiUserRequest.getEducationAttainment();
        if (ValidParam.isNotEmpty(educationAttainment)) {
            String value = ChooseEq.create()
                    .when(educationAttainment, "1", "1")
                    .when(educationAttainment, "2", "3")
                    .when(educationAttainment, "3", "4")
                    .when(educationAttainment, "4", "5")
                    .when(educationAttainment, "5", "6")
                    .end();
            apiUserRequest.setEducationAttainment(value);
        }

        //  job 职业信息：1-自由职业者（默认）；  2-上班族； 3-(公务员/事业/国企) ；4-企业主； 5-个体户
        //  career 职业
        //  1 上班族
        //  2 自由职业
        //  3 企业主（有营业执照）
        //  4 公务员或事业单位
        //  5 个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "1", "2")
                    .when(career, "2", "1")
                    .when(career, "3", "4")
                    .when(career, "4", "3")
                    .when(career, "5", "5")
                    .end();
            apiUserRequest.setCareer(value);
        }

        //  minIncome 最低月收入(单位：元）
        //  monthlySalary 月收入
        //  1 1000-3000
        //  2 3000-8000
        //  3 8000~15000
        //  4 15000~30000
        //  5 30000以上
        String monthlySalary = apiUserRequest.getMonthlySalary();
        if (ValidParam.isNotEmpty(monthlySalary)) {
            apiUserRequest.setMonthlySalary(ApiDictUtils.convertMonthlySalary(monthlySalary));
        }

        //  wages 工资发放形式(0无 1银行卡 2现金 3 银行转账 4微信、支付宝）
        //  (当profession为1或2时，才会有值)
        //  salaryPayMethod 工资发放形式
        //  1 银行代发打卡
        //  2 现金收入
        //  3 个人转账
        String salaryIssueMethod = apiUserRequest.getSalaryPayMethod();
        if (ValidParam.isNotEmpty(salaryIssueMethod)) {
            String value = ChooseEq.create()
                    .when(salaryIssueMethod, "1", "1")
                    .when(salaryIssueMethod, "2", "2")
                    .when(salaryIssueMethod, "3", "3")
                    .when(salaryIssueMethod, "4", "3")
                    .when(salaryIssueMethod, "5", "3")
                    .end();
            apiUserRequest.setSalaryPayMethod(value);
        }

        // jobTime 工龄(上班族、公务员/事业/国企)  0-无 1-(0-6个月) 2-(6-12个月)  3-(12个月以上)
        // yearsService 单位工龄
        // 1 0-6个月
        // 2 6-12个月
        // 3 12个月以上
        String yearsService = apiUserRequest.getYearsService();
        if (ValidParam.isNotEmpty(yearsService)) {
            String value = ChooseEq.create()
                    .when(yearsService, "1", "1")
                    .when(yearsService, "2", "2")
                    .when(yearsService, "3", "3")
                    .end();
            apiUserRequest.setYearsService(value);
        }

        // busLicense 营业执照（0-无  1-两年以下 2-两年以上）
        // bizLicenseYear 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        String bizLicenseYear = apiUserRequest.getBizLicenseYear();
        if (ValidParam.isNotEmpty(bizLicenseYear)) {
            String value = ChooseEq.create()
                    .when(bizLicenseYear, "0", "1")
                    .when(bizLicenseYear, "1", "2")
                    .when(bizLicenseYear, "2", "3")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        //  social 社保（0-无；1-6个月以下； 2-6个月及以上）
        //  socialSecurity 社保缴纳
        //  1 无社保
        //  2 缴纳6个月以下
        //  3 缴纳6个月以上
        //  4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "0", "1")
                    .when(socialSecurity, "1", "2")
                    .when(socialSecurity, "2", "3")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        //  fund 公积金（ 0-无； 1-.未满6个月 ；2-6个月及以上）
        //  providentFund 公积金
        //  1 无公积金
        //  2 缴纳6个月以下
        //  3 缴纳6个月以上
        //  4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "0", "1")
                    .when(providentFund, "1", "2")
                    .when(providentFund, "2", "3")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        //  house 房产信息（0-无；1-按揭房产；2-全款房产）
        //  realEstateInfo 房产情况
        //  1 无房产
        //  2 有房不抵押
        //  3 有房可抵押
        //  4 有房产
        //  5 有按揭房产
        //  6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "0", "1")
                    .when(realEstateInfo, "1", "5")
                    .when(realEstateInfo, "2", "6")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        //  car 车产信息（0-无；1-按揭车；2-全款车）
        //  3：有车且接受抵押
        //  carInfo 车辆情况
        //  1 无车产
        //  2 有车不抵押
        //  3 有车可抵押
        //  4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "0", "1")
                    .when(carInfo, "1", "2")
                    .when(carInfo, "2", "3")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        //  policy 保险保单（0-无；1-1年以内；2-1年以上
        //  insurancePolicy 保险保单
        //  1 无保险保单
        //  2 缴纳未满1年
        //  3 缴纳1年以上
        //  4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "0", "1")
                    .when(insurancePolicy, "1", "2")
                    .when(insurancePolicy, "2", "3")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // creditCard 信用卡（0-无；1-2万元以内；2-2万元以上
        // creditLimit 信用卡额度
        // 1 无信用卡
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        // 6 有信用卡
        String creditLimit = apiUserRequest.getCreditLimit();
        if (ValidParam.isNotEmpty(creditLimit)) {
            String value = ChooseEq.create()
                    .when(creditLimit, "0", "1")
                    .when(creditLimit, "1", "3")
                    .when(creditLimit, "2", "5")
                    .end();
            apiUserRequest.setCreditLimit(value);
        }

        //  sesame 芝麻分（0-未知；1-550分以下； 2-550~599； 3-600~649；4-650~699； 5-700分以上）
        //  sesameCredit 芝麻分
        //  1 600分以下
        //  2 600~649分
        //  3 650~699分
        //  4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "1", "1")
                    .when(sesameCredit, "2", "1")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "3")
                    .when(sesameCredit, "5", "4")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // huabei 花呗（0-无；1-有）
        // hbLimit 蚂蚁花呗可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        String hbLimit = apiUserRequest.getHbLimit();
        if (ValidParam.isNotEmpty(hbLimit)) {
            String value = ChooseEq.create()
                    .when(hbLimit, "0", "1")
                    .when(hbLimit, "1", "2")
                    .end();
            apiUserRequest.setHbLimit(value);
        }

        // baitiao 京东白条（0-无；1-有）
        // btLimit 京东白条可用额度
        // 1 无额度
        // 2 3千以下
        // 3 3千-1万
        // 4 1-3万
        // 5 3万以上
        String btLimit = apiUserRequest.getBtLimit();
        if (ValidParam.isNotEmpty(btLimit)) {
            String value = ChooseEq.create()
                    .when(btLimit, "0", "1")
                    .when(btLimit, "1", "2")
                    .end();
            apiUserRequest.setBtLimit(value);
        }

        // purpose 贷款用途（0-其他； 1-购房；2-结婚； 3-消费； 4-教育培训；5-购车；6-装修；
        // loanPurpose
        // 1 旅游
        // 2 教育
        // 3 婚庆
        // 4 装修
        // 5 医疗
        // 6 个人消费
        String loanPurpose = apiUserRequest.getLoanPurpose();
        if (ValidParam.isNotEmpty(loanPurpose)) {
            String value = ChooseEq.create()
                    .when(loanPurpose, "0", "6")
                    .when(loanPurpose, "1", "6")
                    .when(loanPurpose, "2", "3")
                    .when(loanPurpose, "3", "6")
                    .when(loanPurpose, "4", "2")
                    .when(loanPurpose, "5", "6")
                    .when(loanPurpose, "6", "4")
                    .end();
            apiUserRequest.setLoanPurpose(value);
        }

    }

    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> {
            newMap.put("orderId", apiReceiveNotice.getReqId());
            newMap.put("phoneMd5", apiReceiveNotice.getPhoneMd5());
        });
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        boolean callback = Eq.object(msg, "重复回调") && Eq.object(code, 500);
        return Eq.object(code, 200) || callback;
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return MapUtils.newHashMap(newMap -> {
            newMap.put("orderId", apiReceiveNotice.getReqId());
            newMap.put("phoneMd5", apiReceiveNotice.getPhoneMd5());
        });
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        JSONObject jsonObject = JsonUtils.get(responseBody);
        Integer code = jsonObject.getInteger("code");
        String msg = jsonObject.getString("msg");
        boolean callback = Eq.object(msg, "重复回调") && Eq.object(code, 500);
        return Eq.object(code, 200) || callback;
    }
}
